const WebSocket = require('ws');

const numTables = 6;
const seatsPerTable = 4;
const tables = [];
const players = [];

for (let i = 0; i < numTables; i++) {
  const table = {
    seats: Array(seatsPerTable).fill(null),
    start: false
  };
  tables.push(table);
}

// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ noServer: true });

// 存储所有连接的客户端
const clients = new Set();

// 处理 WebSocket 连接
wss.on('connection', (ws) => {
  clients.add(ws);

  // 当客户端断开连接时，从集合中移除
  ws.on('close', () => {
    clients.delete(ws);
  });
});

// 广播消息给所有连接的客户端
function broadcast(data) {
  const json = JSON.stringify(data);
  clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(json);
    }
  });
}


module.exports = {
  wss: wss,
  tables: tables,
  players: players,
  broadcast: broadcast
};